import itchat, time, requests,random,re
from itchat.content import *
replied=[]
reply_content=""
"""
从聚合接口中获取回复消息
"""
# def getResponse(msg):
#      url="http://op.juhe.cn/robot/index?info="+msg+"&key=4e9a0ffd536418b627719a42d4b14ba1"
#      print(url)
#      response=requests.get(url)
#      print(response)
#      results=response.json()['result']
#      greeting=results['text']
#      return  greeting
"""
图灵机器人聊天
"""
def getResponse(msg):
  Url = 'http://www.tuling123.com/openapi/api'
  data = {
    'key'  :  '84d8d40a6a1146eeb925b33987b42fa8',
    'info'  : msg,
    'userid' : 'pth-robot',
  }
  try:
    r = requests.post(Url, data=data).json()
    return r.get('text')
  except:
    return
def sendGreeting(msg):
   # global replied
   # friend=itchat.search_friends(userName=msg['FromUserName'])
    itchat.send(msg+'1',msg['FromUserName'])
    #replied.append(msg['FromUserName'])


#@itchat.msg_register([TEXT])

@itchat.msg_register([TEXT, PICTURE, MAP, CARD, NOTE, SHARING, RECORDING, ATTACHMENT, VIDEO])
def text_reply(msg):
    if msg['Type']=="Text":
       reply_content = getResponse(msg['Text'])
       itchat.send(reply_content,msg['FromUserName'])
    else:
        if msg['Type'] == "Map":
           x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1,
                                                                                                                    2,
                                                                                                                    3)
           if location is None:
              reply_content = r"位置: 纬度->" + x.__str__() + " 经度->" + y.__str__()
           else:
               reply_content = r"位置: " + location
        elif msg['Type'] == 'Card':
           reply_content = r" " + msg['RecommendInfo']['NickName'] + r" 的名片"
        elif msg['Type'] == 'Recording':
           reply_content = r"语音"
        elif msg['Type'] == 'Attachment':
           reply_content = r"文件: " + msg['FileName']
        elif msg['Type'] == 'Video':
           reply_content = r"视频: " + msg['FileName']
        elif msg['Type'] == 'Picture':
           reply_content = r"图片: " + msg['FileName']
        itchat.send(r"我已经收到你在【%s】发送的消息【%s】稍后回复。--微信助手(Python版)" % (time.ctime(), reply_content),
              msg['FromUserName'])

@itchat.msg_register(TEXT,isGroupChat=True)
def text_replay(msg):
    if msg.isAt:
       reply_content = getResponse(msg['Text'])
       itchat.send(reply_content, msg['FromUserName'])
     #  itchat.send("收到",toUserName=msg["FromUserName"])
itchat.auto_login(hotReload=True)
itchat.run()